package com.ruoyi.web.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <br>
 *
 * @author chenwujie
 * @date 2021/2/11
 */
public class LocalDateTimeUtils {
    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static final String YYYY_MM_DD = "yyyy-MM-dd";

    static final DateTimeFormatter df_YYYY_MM_DD_HH_MM_SS = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);
    static final DateTimeFormatter df_YYYY_MM_DD = DateTimeFormatter.ofPattern(YYYY_MM_DD);

    public static void main(String[] args) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.now();
        String localTime = df.format(time);
        LocalDateTime ldt = LocalDateTime.parse("2018-01-12 17:07:05", df);
        System.out.println("LocalDateTime转成String类型的时间：" + localTime);
        System.out.println("String类型的时间转成LocalDateTime：" + ldt);
    }

    public static String dateTime2String(LocalDateTime dateTime) {
        return df_YYYY_MM_DD_HH_MM_SS.format(dateTime);
    }

    public static String dateTime2DateString(LocalDateTime dateTime) {
        return df_YYYY_MM_DD.format(dateTime);
    }

    public static String dateTime2DateString(LocalDate localDate) {
        return df_YYYY_MM_DD.format(localDate);
    }

    public static LocalDate parse2Date(String dateStr) {
        try {
            return LocalDate.parse(dateStr, df_YYYY_MM_DD);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static LocalDateTime parse2Datetime(String dateStr) {
        try {
            return LocalDateTime.parse(dateStr, df_YYYY_MM_DD_HH_MM_SS);
        } catch (Exception e) {
            return null;
        }
    }
}
